package com.simdo.g768.Adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;


import com.simdo.g768.Bean.IMSIState;
import com.simdo.g768.Bean.ImsiBean;
import com.simdo.g768.Listener.BeanClickListener;
import com.simdo.g768.MainActivity;
import com.simdo.g768.R;
import com.simdo.g768.Util.DateUtil;
import com.simdo.g768.ZApplication;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ImsiAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private final Context context;
    private final List<ImsiBean> dataList;
    private final List<ImsiBean> uiDataList;
    private BeanClickListener mOnItemClickListener; //单击事件

    private final int nr_icon, lte_icon;
    private final int color_b6b6b6, main_color;
    private final int red, color_47a2ba, color_1c1c1c;
    private final Drawable iphone;
    private final Drawable sansung;

    public ImsiAdapter(Context context, List<ImsiBean> dataList) {
        this.context = context;
        this.dataList = dataList;
        this.uiDataList = new ArrayList<>();
        nr_icon = R.mipmap.nr_icon;
        lte_icon = R.mipmap.lte_icon;
        color_b6b6b6 = context.getResources().getColor(R.color.color_b6b6b6);
        main_color = context.getResources().getColor(R.color.main_color);
        red = context.getResources().getColor(R.color.red);
        color_47a2ba = context.getResources().getColor(R.color.color_47a2ba);
        color_1c1c1c = context.getResources().getColor(R.color.color_1c1c1c);
        iphone = context.getResources().getDrawable(R.mipmap.iphone);
        sansung = context.getResources().getDrawable(R.mipmap.sansung);
        // 这一步必须要做,否则不会显示.
        iphone.setBounds(0, 0, iphone.getMinimumWidth() / 3, iphone.getMinimumHeight() / 3);
        sansung.setBounds(0, 0, sansung.getMinimumWidth() / 3, sansung.getMinimumHeight() / 3);
    }

    @Override
    public int getItemCount() {
        return !uiDataList.isEmpty() ? uiDataList.size() : 1;//不同点4,也是关键点
    }

    @Override
    public int getItemViewType(int position) {
        if (uiDataList.isEmpty()) return -1;
        return super.getItemViewType(position);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof EmptyHolder) return;
        final ViewHolder viewHolder = (ViewHolder) holder;

        final int pos = position;
        // 渲染数据
        ImsiBean item = uiDataList.get(pos);

        viewHolder.iv_nr_lte.setImageResource(Integer.parseInt(item.getArfcn()) > 100000 ? nr_icon : lte_icon);
        String imsi = item.getImsi();
        if (!ZApplication.getInstance().isShowAllImsi) imsi = imsi.substring(0,5) + "****" + imsi.substring(11);
        viewHolder.tv_imsi.setText(item.getNotes().isEmpty() ? MessageFormat.format("{0}", imsi) : MessageFormat.format("{0}\n{1}", imsi, item.getNotes()));

        Drawable drawable = null;
        if (item.getRsrp() > MainActivity.getInstance().showMinRsrp){
            switch (item.getPhone_type()){
                case 2:
                case 3:
                case 4:
                    drawable = iphone;
                    break;
                case 5:
                case 12:
                    drawable = sansung;
                    break;
            }
        }
        viewHolder.tv_imsi.setCompoundDrawables(null, null, drawable, null);

        viewHolder.iv_nr_lte_band.setImageResource(item.getIcon());
        viewHolder.tv_rsrp.setText(MessageFormat.format("{0}", String.valueOf(item.getRsrp())));
        viewHolder.tv_rsrp.setTextColor(newTime - item.getLatestTime() > 5000 ? color_b6b6b6 : main_color);
        viewHolder.tv_end_info.setText(MessageFormat.format("{0}/{1}\n" + /*"\n{2}"*/context.getString(R.string.count)+"\n{3}", item.getArfcn(), item.getPci(), item.getUpCount(), DateUtil.formateTimeHMS(item.getLatestTime())));
        int color = IMSIState.IMSI_OLD;
        switch (item.getState()) {
            case IMSIState.IMSI_NEW:
            case IMSIState.IMSI_OLD:
                color = color_1c1c1c;
                break;
            case IMSIState.IMSI_NOW:
                color = red;
                break;
            case IMSIState.IMSI_BL:
            case IMSIState.IMSI_NOW_BL:
                color = color_47a2ba;
                break;
        }
        //if (!ZApplication.getInstance().isTrace && newSelect.equals(item.getImsi())) color = context.getResources().getColor(R.color.red);
        viewHolder.tv_imsi.setTextColor(color);
        viewHolder.tv_imsi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mOnItemClickListener!=null) mOnItemClickListener.onItemClickListener(view, uiDataList.get(pos));
            }
        });
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup arg0, int arg1) {
        if (-1 == arg1)
            return new EmptyHolder(LayoutInflater.from(context).inflate(R.layout.item_empty, arg0, false));

        View item = LayoutInflater.from(context).inflate(R.layout.item_imsi, arg0, false);
        return new ViewHolder(item);
    }

    /**
     * 暴露给外面的设置单击事件
     */
    public void setOnItemClickListener(BeanClickListener onItemClickListener) {
        mOnItemClickListener = onItemClickListener;
    }

    public void updateImsi(ImsiBean bean, boolean setNull){
        if (setNull){
            for (int i = 0; i < dataList.size(); i++){
                if (dataList.get(i).getState() == 3) {
                    dataList.get(i).setState(0);
                    break;
                }
            }
        }else {
            boolean isBreak = false;
            for (int i = 0; i < dataList.size(); i++){
                if (dataList.get(i).getState() == 3) {
                    dataList.get(i).setState(0);
                    if (isBreak) break;
                    isBreak = true;
                }

                if (bean.getImsi().equals(dataList.get(i).getImsi())) {
                    dataList.get(i).setState(3);
                    if (isBreak) break;
                    isBreak = true;
                }
            }
        }
        notifyDataSetChanged();
    }
    long newTime = System.currentTimeMillis();

    public void setSortMode(int sortMode) {
        this.sortMode = sortMode;
        resetShowData();
    }

    public int getSortMode() {
        return sortMode;
    }

    int sortMode = 0;
    @SuppressLint("NotifyDataSetChanged")
    public synchronized void resetShowData() {
        if (sortMode == 0) {
            quickSort(0, dataList.size() - 1);

            List<ImsiBean> allList = new ArrayList<>(dataList);

            uiDataList.clear();
            int nowCount = 0;
            int nowAndBlCount = 0;
            long bl_time = 0; //黑名单按时间排序
            long time = 0; //其他按时间排序
            //排序  当前定位靠前， 黑名单紧次， 其他按时间排序靠后
            newTime = System.currentTimeMillis();
            boolean isTrace = ZApplication.getInstance().isTrace;
            for (ImsiBean bean : allList) {
                int state = bean.getState();
                if (state == IMSIState.IMSI_NOW) {
                    uiDataList.add(nowCount, bean);
                    nowCount += 1;
                    nowAndBlCount += 1;
                } else if (isTrace && state == IMSIState.IMSI_BL) {
                    if (bean.getLatestTime() > bl_time) {
                        bl_time = bean.getLatestTime();
                        uiDataList.add(nowCount, bean);
                    } else uiDataList.add(nowAndBlCount, bean);
                    nowAndBlCount += 1;
                } else {
                    if (bean.getRsrp() != -1/* && bean.getLatestTime() > time*/ && newTime - bean.getLatestTime() < 5000) {
                        //time = bean.getLatestTime();
                        uiDataList.add(nowAndBlCount, bean);
                    } else uiDataList.add(bean);
                }
            }
        } else if (sortMode == 1) {
            quickSortCount(0, dataList.size() - 1);
            uiDataList.clear();
            uiDataList.addAll(dataList);
        } else {
            quickSortTime(0, dataList.size() - 1);
            uiDataList.clear();
            uiDataList.addAll(dataList);
        }

        notifyDataSetChanged();
    }

    //快排实现方法
    private void quickSort(int low, int high) {
        int i, j, pivot;
        //结束条件
        if (low >= high) return;
        i = low;
        j = high;
        //选择的节点，这里选择的数组的第一数作为节点
        pivot = dataList.get(low).getRsrp();
        while (i < j) {
            //从右往左找比节点小的数，循环结束要么找到了，要么i=j
            while (dataList.get(j).getRsrp() >= pivot && i < j) {
                j--;
            }
            //从左往右找比节点大的数，循环结束要么找到了，要么i=j
            while (dataList.get(i).getRsrp() <= pivot && i < j) {
                i++;
            }
            //如果i!=j说明都找到了，就交换这两个数
            if (i < j) Collections.swap(dataList, i, j);
        }
        //i==j一轮循环结束，交换节点的数和相遇点的数
        Collections.swap(dataList, low, i);
        //数组“分两半”,再重复上面的操作
        quickSort(low, i - 1);
        quickSort(i + 1, high);
    }

    //快排实现方法
    private void quickSortCount(int low, int high) {
        int i, j, pivot;
        //结束条件
        if (low >= high) {
            return;
        }
        i = low;
        j = high;
        //选择的节点，这里选择的数组的第一数作为节点
        pivot = dataList.get(low).getUpCount();
        while (i < j) {
            //从右往左找比节点大的数，循环结束要么找到了，要么i=j
            while (dataList.get(j).getUpCount() <= pivot && i < j) {
                j--;
            }
            //从左往右找比节点小的数，循环结束要么找到了，要么i=j
            while (dataList.get(i).getUpCount() >= pivot && i < j) {
                i++;
            }
            //如果i!=j说明都找到了，就交换这两个数
            if (i < j) {
                Collections.swap(dataList, i, j);
            }
        }
        //i==j一轮循环结束，交换节点的数和相遇点的数
        Collections.swap(dataList, low, i);
        //数组“分两半”,再重复上面的操作
        quickSortCount(low, i - 1);
        quickSortCount(i + 1, high);
    }

    //快排实现方法
    private void quickSortTime(int low, int high) {
        int i, j;
        long pivot;
        //结束条件
        if (low >= high) {
            return;
        }
        i = low;
        j = high;
        //选择的节点，这里选择的数组的第一数作为节点
        pivot = dataList.get(low).getLatestTime();
        while (i < j) {
            //从右往左找比节点大的数，循环结束要么找到了，要么i=j
            while (dataList.get(j).getLatestTime() <= pivot && i < j) {
                j--;
            }
            //从左往右找比节点小的数，循环结束要么找到了，要么i=j
            while (dataList.get(i).getLatestTime() >= pivot && i < j) {
                i++;
            }
            //如果i!=j说明都找到了，就交换这两个数
            if (i < j) {
                Collections.swap(dataList, i, j);
            }
        }
        //i==j一轮循环结束，交换节点的数和相遇点的数
        Collections.swap(dataList, low, i);
        //数组“分两半”,再重复上面的操作
        quickSortTime(low, i - 1);
        quickSortTime(i + 1, high);
    }

    static class ViewHolder extends RecyclerView.ViewHolder {

        ImageView iv_nr_lte;
        ImageView iv_nr_lte_band;
        TextView tv_end_info;
        TextView tv_imsi;
        TextView tv_rsrp;

        public ViewHolder(View itemView) {
            super(itemView);
            iv_nr_lte = itemView.findViewById(R.id.iv_nr_lte);
            iv_nr_lte_band = itemView.findViewById(R.id.iv_nr_lte_band);

            tv_end_info = itemView.findViewById(R.id.tv_end_info);
            tv_imsi = itemView.findViewById(R.id.tv_imsi);
            tv_rsrp = itemView.findViewById(R.id.tv_rsrp);
        }
    }

    /**
     * 空数据显示的   不同点1
     */
    static class EmptyHolder extends RecyclerView.ViewHolder {

        public EmptyHolder(View itemView) {
            super(itemView);
        }

    }
}
